import Request from './request'
import configure from '@/config.js'
import store from '@/store/index.js'
import md5 from '@/utils/md5/md5.js'
import {weBtoa, weAtob} from '@/utils/jwt/jwt.js'
import { getProt } from '@/utils/utils.js'
import loginPath from "@/utils/login_path.js"

const http = new Request()

let baseUrl, client_id, client_secret,platform_no

    platform_no = getProt()
// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
let config = configure.miniProgram
	baseUrl = config.baseUrl
	client_id = config.client_id
	client_secret = config.client_secret
// #endif
    
// #ifdef H5
if (configure.devMode) {
	baseUrl = configure.h5.cmsUrl
} else {
	baseUrl = configure.h5.baseUrl
}
// #endif

/* 全局配置, 适用于设置基本不变的固定数据，如果是动态变化则在请求拦截中配置 */
http.setConfig((config) => {
	config.baseUrl = baseUrl
	config.header = {
		'Content-Type': 'application/json'
	}
	config.method = 'GET'
	config.dataType = 'json'
	config.responseType = 'text'
	return config
})

/* 请求拦截器 */
http.interceptor.request((config, cancel) => {
	
	// #ifdef H5
	client_id = uni.getStorageSync('client_id')
	client_secret = uni.getStorageSync('client_secret')
	// #endif
	
	const token = uni.getStorageSync('token') || ''
	const is_direct = 1
	const timestamp = Date.now()

	// 指定请求url, 设置为method的value
	config.url = config.data.method	

	// 用加密的签名替换明文参数
	config.data = {
		...config.data,
		client_id,
		client_secret,
		token,
		timestamp
	}
	return config
})

/* 响应拦截器 */
http.interceptor.response((response) => {
	let data = null;
	data = response.data.data
	response.data = data
	
	return response.data
}, (response) => { // 请求错误做点什么
	return response
})

/**
 * @param {Object} params 参数转base64
 * @description 签名需要的body字符串
 */
const paramToBase64 = function(params = {}) {
	return weBtoa(JSON.stringify(params))
}

/**
 * @param {String} params base64字符串
 * @description 把base64转为对象
 */
const base64ToResponse = function(base64 = '') {
	return JSON.parse(weAtob(base64))
}

export default http